package com.cskaoyan.factory;

import com.cskaoyan.dao.UserDao;
import lombok.Data;
import org.springframework.beans.factory.FactoryBean;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author stone
 * @date 2022/08/02 09:37
 */
@Data
public class UserDaoProxyFactoryBean implements FactoryBean<UserDao> {

    Object target;//委托类对象 → set方法

    @Override
    public UserDao getObject() throws Exception {
        // 生成代理对象 需要委托类对象
        Object proxy = Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("hello");
                //method.invoke(proxy, args);
                Object invoke = method.invoke(target, args);
                System.out.println("byebye");
                return invoke;
            }
        });

        return (UserDao) proxy;
    }

    @Override
    public Class<?> getObjectType() {
        return UserDao.class;
    }
}
